<?php

class UserController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        // stijlen koppelen
        $this->stylesBase = $this->view->baseUrl() . '/styles/';
    }

    public function preDispatch()
    {
        if(isset(Zend_Auth::getInstance()->getStorage()->read()->user_role))
        {
            $role = Zend_Auth::getInstance()->getStorage()->read()->user_role;
        
        }
        
        if(zend_auth::getInstance()->hasIdentity()){
            switch ($this->getRequest()->getActionName()) {
                case 'registration':
                    break;
                case 'logout':
                    break;
                case 'list':
                    if($role !='admin')
                    {
                        $this->_helper->redirector('index', 'index');
                    }
                    break;
                case 'details':
                    if($role !='admin')
                    {
                        $this->_helper->redirector('index', 'index');
                    }
                    break;
                case 'suspenduser':
                    if($role !='admin')
                    {
                        $this->_helper->redirector('index', 'index');
                    }
                    break;
                case 'unsuspenduser':
                    if($role !='admin')
                    {
                        $this->_helper->redirector('index', 'index');
                    }
                    break;
                case 'deleteuser':
                    if($role !='admin')
                    {
                        $this->_helper->redirector('index', 'index');
                    }
                    break;
                default:
                        $this->_helper->redirector('index', 'index');
                    break;

            }
        }
        else {
            // Uitloggen kan niet als je niet uitgelogd bent.
            switch ( $this->getRequest()->getActionName() ) {
                case 'index':
                    break;
                case 'registration':
                    break;
                case 'add':
                    break;
                case 'auth':
                    break;
                default: $this->_helper->redirector('index');
                    break;
            }
        }
            
        
    }

    public function indexAction()
    {
        $view = $this->_getView('Login');
        $form = new Application_Form_Login(array(
            'action' => $this->view->baseUrl() . '/user/auth', // controller user, actie auth
            'method' => 'post',
        ));
        $view->form = $form;
        
        
        
    }

    public function detailsAction()
    {
        $request = $this->getRequest();
        $form = new Application_Form_Userdetails();
        
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($request->getPost())) {
                $user = new Application_Model_User($form->getValues());
                $mapper  = new Application_Model_UserMapper();
                $mapper->save($user);
                return $this->_helper->redirector('list');
            }
        }
        
        // action body
        
        $currentuserid = $request->getParam('userid');
        
        //$form->populate($this->getRequest()->getParam('userid'));
        $view = $this->_getView('Userdetails');
        $view->form = $form;
        $usermapper = new Application_Model_UserMapper();
        $user = new Application_Model_User();
        $user = ($usermapper->fetchById($currentuserid));
        $populatearray = array(
            'email'         => $user->getEmail(),
            'givenname'     => $user->getGivenname(),
            'familyname'    => $user->getFamilyname(),
            'id'            => $user->getId(),
            'active'        => $user->getActive(),
            'role'          => $user->getRole(),
            'deleted'       => $user->getDeleted(),
            'creationdate'  => $user->getCreationdate(),
        );
        
        $form->populate($populatearray);
    }

    public function authAction()
    {
        $request = $this->getRequest(); // requestobject
        
        $view = $this->_getView('Error - Login'); //view instellen

        $form =  new Application_Form_Login(array(
            'action' => $this->view->baseUrl() . '/user/auth', // controller user, actie auth
            'method' => 'post',
        ));// loginform

        // Formulier valideren
        if ( !$form->isValid($request->getPost() ) ) {
            $this->view->form = $form; // loginform terug tonen
            return $this->render('index'); // Render index view script
        }
        
        // Gebruikersauthentificatie
        $values = $form->getValues();
        
        
        $adapter = new Ahs_Auth_Adapter_DbTable();
        $adapter->setIdentity($values['email'])
                    ->setCredential($values['password']);
        
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($adapter);
        if ( !$result->isValid() ) {
            $form->setDescription('Wrong email and/or password');
            $this->view->form = $form;
            return $this->render('index'); // Render index view script
        } else {
            $storage = $auth->getStorage();
            $storage->write( $adapter->getResultRowObject(array(
                'user_role',
                'user_givenname',
                'user_familyname',
                'user_id',
            )));
            
            if($storage->read()->user_role == 'admin')
            {
                return $this->_helper->redirector('list', 'user');
            }
            else
            {
                return $this->_helper->redirector('list', 'project');
            }
        }
        
        
        
        
         
         
        
    }

    public function listAction()
    {
        $storage = $storage = Zend_Auth::getInstance()->getStorage()->read();
        
        // action body
        $view = $this->_getView('Userlist');
        $view->role = $storage->user_role;
        $request = $this->getRequest();
        $usermapper = new Application_Model_UserMapper();
        $searchform = new Application_Form_Search();
        $useractionform = new Application_Form_Useraction();
        $view->searchform = $searchform;
        $view->useractionform = $useractionform; 
        if ($this->getRequest()->isPost() && $searchform->isValid($request->getPost()) && $searchform->getValue('searchtext') != '')  {
            
                
                $this->view->entries = $usermapper->fetchBySearchstring($searchform->getValue('searchtext'));
            
        }
        else
        {
            $this->view->entries = $usermapper->fetchAll();
        }
        
        $view->headLink()->prependStylesheet('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css');
        
    }

    public function registrationAction()
    {
        // action body
        $view = $this->_getView('Register as projectowner');
        $form = new Application_Form_Registration(array(
            'action' => $this->view->baseUrl('user/add'),
            'method' => 'post',
        ));
        $view->form = $form;
        
        
        
    
    }

    public function addAction()
    {
        //
        $form = new Application_Form_Registration(array(
            'action' => $this->view->baseUrl('user/add'),
            'method' => 'post',
        ));
        $view= $this->_getView('Registrationerror');
        
        if (!$form->isValid($this->getRequest()->getPost())) {
            $view-> form = $form;
            
            return $this->render('registration');
            
        }
        else
        {
            
            $user = new Application_Model_User($form->getValues());
            $user->Role = 'projectmanager';
            $user->Creationdate = date("Y-m-d H:i:s");
            $user->Deleted = 0;
            $user->Active = 1;
            
            $mapper  = new Application_Model_UserMapper();
            $mapper->save($user);
            return $this->_helper->redirector('index');
        }
        
    }

    public function logoutAction()
    {
        // action body
        Zend_Auth::getInstance()->clearIdentity();
        return $this->_helper->redirector('index');
    }

    public function deleteuserAction()
    {
        $this->_helper->layout()->disableLayout();       // Layout uitschakelen
        $this->_helper->viewRenderer->setNoRender(true);
        
        $request = $this->getRequest();
        
        // variabelen uit request halen, deze zijn verplich
        $userid = $request->getParam('userid');
        
        if($userid !== null)
        {
            $usermapper = new Application_Model_UserMapper();
            if($usermapper->delete($userid))
            {
                echo 'User deleted';
            }
            else
            {
                echo 'User was already deleted';
            }
        }
        else
        {
            echo 'There was an error';
        }
        
    }

    public function suspenduserAction()
    {
        $this->_helper->layout()->disableLayout();       // Layout uitschakelen
        $this->_helper->viewRenderer->setNoRender(true);
        
        $request = $this->getRequest();
        
        // variabelen uit request halen, deze zijn verplich
        $userid = $request->getParam('userid');
        
        if($userid !== null)
        {
            $usermapper = new Application_Model_UserMapper();
            if($usermapper->suspend($userid))
            {
                echo 'User suspended';
            }
            else
            {
                echo 'User was already suspended';
            }
        }
        else
        {
            echo 'There was an error';
        }
        
    }
    
    public function unsuspenduserAction()
    {
        $this->_helper->layout()->disableLayout();       // Layout uitschakelen
        $this->_helper->viewRenderer->setNoRender(true);
        
        $request = $this->getRequest();
        
        // variabelen uit request halen, deze zijn verplich
        $userid = $request->getParam('userid');
        
        if($userid !== null)
        {
            $usermapper = new Application_Model_UserMapper();
            if($usermapper->unsuspend($userid))
            {
                echo 'User unsuspended';
            }
            else
            {
                echo 'User was already suspended';
            }
        }
        else
        {
            echo 'There was an error';
        }
    }
    
    private function _getView($title)
    {
        
        $view = $this->view; // view instellen
        $view->title = $title; // titel instellen op meegegeven waarde
        $view->headTitle($view->title, 'prepend'); // titel van pagina instellen
        $view->headLink()->appendStylesheet($this->stylesBase . 'main.css'); // stylesheets koppelen in de head

        return $view; // return het viewobject
        
        
    }

    


}



















